﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using EQEmu.Database;

namespace EQEmu.Grids
{
    public class ZoneGridsDatabase : ZoneGrids
    {
        private EQEmuContext _context = null;

        public ZoneGridsDatabase(int zoneId, EQEmuContextFactory factory)
            : base(zoneId)
        {
            _context = factory.Create();
            var grids = _context.grid.Where(x => x.zoneid == ZoneId).ToArray();
            foreach (var grid in grids)
            {
                _grids.Add(new GridDatabase(grid, _context));                
            }
        }

        public static ZoneGridsDatabase Create(string zoneName,EQEmuContextFactory factory)
        {
            using (var context = factory.Create())
            {
                var zone = context.zone.FirstOrDefault(x => x.short_name == zoneName);
                if (zone == null) throw new ArgumentException("Cannot find zone name in zone table:" + zoneName);
                return new ZoneGridsDatabase(zone.zoneidnumber, factory);
            }
        }

        public override Grid CreateGrid()
        {
            var grid = _context.grid.CreateObject();
            grid.zoneid = ZoneId;
            return new GridDatabase(grid, _context);
        }

        public override void AddGrid(Grid grid)
        {
            base.AddGrid(grid);
            _context.grid.AddObject(grid.GridValue);
        }

        public override void RemoveGrid(Grid grid)
        {
            base.RemoveGrid(grid);
            _context.grid.DeleteObject(grid.GridValue);
        }
    }
}
